<?php
/**
 * @filename DefaultController.php
 * @author wankang <wankang@dodoca.com>
 * @datetime 2016/4/21 13:53
 * @description 会员卡
 */
class Member_CardController extends SellerController
{
    private $sellerId;
    private $userId;
    private $shopId;
    private $cardModel;
    private $memberCardModel;
    public function init()
    {
        parent::init();
        
        $this->sellerId = $this->getCurrentUser()->getSellerId();
        $this->userId = $this->getCurrentUser()->get('id');
        $this->shopId = $this->getCurrentUser()->getShopId();
        $this->cardModel = User_CardService::getAttrModel();
        $this->memberCardModel = User_CardService::getMemberCardModel();
    }
    
    //会员卡列表
    public function indexAction()
    {
        $list = $this->cardModel->select(array('seller_id'=>$this->sellerId,'status'=>1),array(), null, 'level asc');
        $data['list'] = array();
        if(!empty($list))
        {
        	$cardId = '';
            foreach ($list as $v)
            {
            	$cardId .= ','.$v['id'];
            }
            $cardId = trim($cardId,',');
            $nowT = SYS_TIME;
            $sql = "SELECT
						COUNT(`id`) AS total,
						card_id
					FROM
						ts_user_member
					WHERE
						card_id IN ($cardId)
					AND `status` = 1
					AND (
						`ts_user_member`.pay_end_time IS NULL
						OR `ts_user_member`.pay_end_time = 0
						OR (
							`ts_user_member`.pay_type IN (3, 4)
							AND `ts_user_member`.pay_end_time > $nowT
							AND `ts_user_member`.pay_start_time < $nowT
						) )
					GROUP BY card_id";
            $countArr = $this->memberCardModel->fetchAll($sql);
            $cardCount = array();
            if($countArr)
            {
            	foreach ($countArr as $v)
            	{
            		$cardCount[$v['card_id']] = $v['total'];
            	}
            }
            foreach ($list as &$val)
            {
            	if($cardCount[$val['id']])
            	{
            		$val['total'] = $cardCount[$val['id']];
            	}
            	else
            	{
            		$val['total'] = 0;
            	}
            	
            }
        }
        $data['list'] = $list;
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/card/index.html');
    }
    
    public function ajaxCheckGradeAction($grade = null)
    {
    	try 
    	{
    		if(!$grade)
    		{
    			$grade = $this->_request->getPost('grade');
    		}
    		
    		if(!(int)$grade)
    		{
    			throw new Exception('参数缺失');
    		}
    		$levels = $this->cardModel->select(array('seller_id'=>$this->sellerId,'status'=>1), array('level'));
    		if(!empty($levels))
    		{
    			foreach ($levels as $v)
    			{
    				if($v['level'] == $grade)
    				{
    					throw new Exception('等级重复，请重新填写');
    				}
    			}
    			foreach ($levels as $v)
    			{
    				if($v['level'] < $grade)
    				{
    					$this->ajaxReturn(array('code'=>2,'msg'=>'非最低等级'));
    					break;
    				}
    			}
    		}
    		$this->ajaxReturn(array('code'=>1,'msg'=>'success'));
    	}
    	catch (Exception $e)
    	{
    		$this->ajaxReturn(array('code'=>-1,'msg'=>$e->getMessage()));
    	}
    }
    
    //会员卡领取记录
    public function recordAction()
    {
        $params = $this->_request->getQuery();
        $page = max(intval($params['page']),1);
        $pageSize = 10;
        $where['seller_id'] = $this->sellerId;
        $where['shop_id'] = $this->shopId;
        //查询条件
        if(!empty($params['card_no']))
        {
            $where['card_no'] = array('like','%'.$params['card_no'].'%');
        }
        if($params['card_type'])
        {
            $where['card_id'] = $params['card_type'];
        }
        if(!empty($params['start_time']) && !empty($params['end_time']))
        {
            $startTime = (int)strtotime($params['start_time']);
            $endTime = (int)(strtotime($params['end_time']) + 3600 * 24 - 1);
            $where['create_time'] = array('between', "$startTime,$endTime");
        }
        elseif(!empty($params['start_time']) && empty($params['end_time']))
        {
            $startTime = (int)strtotime($params['start_time']);
            $where['create_time'] = array('EGT', $startTime);
        }
        elseif(empty($params['start_time']) && !empty($params['end_time']))
        {
            $endTime = (int)(strtotime($params['end_time']) + 3600 * 24 - 1);
            $where['create_time'] = array('ELT', $endTime);
        }
        
        $list = $this->memberCardModel->listPage($where, array('card_id','fans_id','create_time','card_no'),'create_time desc',$page,$pageSize);
        if(!empty($list))
        {
            foreach ($list as $k=>$v)
            {
                //获取粉丝信息
                $userInfo = WeiXin_WxUserService::getFansInfo($v['fans_id'], $this->sellerId);
                //获取会员卡信息
                $cardInfo = User_CardService::getCardInfo($v['card_id']);
                $list[$k]['create_time'] = date('Y-m-d H:m:s',$v['create_time']);
                $list[$k]['user_name'] = $userInfo['nick_name'];
                $list[$k]['phone'] = $userInfo['phone'];
                $list[$k]['card_name'] = $cardInfo['card_name'];
                
            }
        }
        //查询会员卡信息
        $cardList = User_CardService::getListBySellerId($this->sellerId);
        
        $total = $this->memberCardModel->count($where);
        $data['list'] = $list;
        $data['page'] = $page;
        $data['totalPage'] = ceil($total / $pageSize);
        $data['total'] = $total;
        $data['card_list'] = $cardList;
        //输出查询条件
        $where['start_time'] = $params['start_time'];
        $where['end_time'] = $params['end_time'];
        $where['card_no'] = $params['card_no'];
        $data['where'] = $where;
        
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/card/record.html');
    }

    /**
     * @author qiankun
     * @Fuction name increaseAction
     * @description 新建会员卡
     */
    public function increaseAction()
    {
        if($this->_request->isXmlHttpRequest())
        {
            try 
            {
                $postData = $this->_request->getPost();
                if(!Tool_Form::checkToken($postData['token']))
                {
                    throw new Exception('请勿重复提交');
                }
                if(!$postData['card_name'])
                {
                    throw new Exception('会员卡名称不能为空');
                }
                //验证等级是否重复
                $data['level'] = (int)$postData['level'];
                if(!$this->checkLevel($data['level']) || $data['level'] <= 0)
                {
                    throw new Exception('会员等级重复，请重新填写');
                }

                //验证会员折扣
                if($postData['discount'] > 10 || $postData['discount'] < 0)
                {
                	throw new Exception('请正确填写会员折扣：0-10');
                }


                //付费会员
                $where = array(
                    'seller_id' => $this->sellerId,
                    'status' => 1,
                    'type' => array('in',array(2,3,4))
                );
                $payCount = $this->cardModel->count($where);
                //免费会员
                $where = array(
                    'seller_id' => $this->sellerId,
                    'status' => 1,
                    'type' => 1
                );
                $noPayCount = $this->cardModel->count($where);
                //免费会员类型
                if($postData['member_card_type'] == 1)
                {
                	if($payCount)
                	{
                		throw new Exception('已含付费类型会员卡，不能新建无需付费类型会员卡');
                	}
                    
                    //免费会员
                    $data['type'] = 1;
                    if($postData['integral'] === '' )
                    {
                        throw new Exception('积分限制不能为空');
                    }
                    if($postData['integral'] > 0 && !$this->checkIntegral($postData['integral'], $data['level']))
                    {
                        throw new Exception('高等级会员卡必须比低等级会员卡积分高');
                    }

                }
                else if( $postData['member_card_type'] == 2) //付费会员类型
                {
                	if($noPayCount)
                	{
                		throw new Exception('已含有无需付费类型会员卡，不能新建付费类型会员卡');
                	}
                    //付费会员
                    if(!$pay_type = intval($postData['pay_type']))
                    {
                        throw new Exception('请填写付费类型');
                    }
                    else
                    {
                        $payDiscount = $postData['pay_discount'];
                        if($payDiscount > 10 || $payDiscount < 0)
                        {
                            throw new Exception('续费折扣格式错误');
                        }

                        if($postData['price'] == '')
                        {
                            throw new Exception('未填写金额');
                        }
                        //正整数包含0
                        if(!Tool_Validator::isPositiveInteger($postData['price']) && $postData['price'] !=0)
                        {
                            throw new Exception('付费金额必须为整数');
                        }
                        if(!is_numeric($postData['price']) || $postData['price'] < 0)
                        {
                            throw new Exception('请填写正确的金额');
                        }
                        if($postData['price']* $postData['pay_discount'] != 0 && $postData['pay_discount'] <0.01)
                        {
                            throw new Exception( '折扣后的价格不能低于0.01');
                        }

                        $data['pay_discount'] = $payDiscount*10;
                        $data['price'] =  intval($postData['price']);
                        switch($pay_type)
                        {
                            case 1:
                                $data['type'] = 2;
                                break;
                            case 2:
                                $data['type'] = 3;
                                if($pay_month = intval($postData['pay_month']))
                                {
                                    $data['pay_month'] = $pay_month; //时间区间
                                    $data['pay_start_time'] = 0;
                                    $data['pay_end_time'] = 0;
                                }
                                else
                                {
                                    throw new Exception('请填写月份');
                                }
                                break;
                            case 3:
                                $data['type'] = 4;
                                if(!$postData['end_time'] || !$postData['start_time'])
                                {
                                    throw new Exception('填写开始和结束时间');
                                }
                                if($postData['end_time'] < $postData['start_time'])
                                {
                                    throw new Exception('结束时间必须大于开始时间');
                                }
                                $data['pay_start_time'] = $postData['start_time'] ? strtotime($postData['start_time']) : 0;
                                $data['pay_end_time'] = $postData['start_time'] ? strtotime($postData['end_time'])+24*3600-1 : 0;
                                break;
                            default:
                                throw new Exception('未选择对应的付费类型');
                        }
                    }
                }
                else
                {
                    throw new Exception('未选择会员卡类型');
                }
                //付费会员验证end

                $data['background_color'] = $postData['background_color'];
                $data['card_name'] = $postData['card_name'];
                //$data['type'] = $postData['type'];
                $data['pic_id'] = $postData['pic_id'];
                $data['discount'] = $postData['discount'] * 10;
                $data['is_freepost'] = $postData['is_freepost'];
                $data['fans_integral'] = $postData['integral'];
                
                $postData['fans_consumption'] && $data['fans_consumption'] = $postData['fans_consumption'];
                $postData['fans_times'] && $data['fans_times'] = $postData['fans_times'];
                
                $postData['reward_integral'] && $data['reward_integral'] = $postData['reward_integral'];
                $postData['reward_consumption'] && $data['reward_consumption'] = $postData['reward_consumption'];
                $postData['reward_coupon_id'] && $data['reward_coupon_id'] = $postData['reward_coupon_id'];
                $data['phone'] = $postData['phone'];

                $data['terms'] = $postData['terms'];
                $data['seller_id'] = $this->sellerId;
                $data['create_user'] = $this->userId;
                $data['create_time'] = SYS_TIME;
                //var_dump($data);exit();
                $id = $this->cardModel->insertData($data);
                if($id)
                {
                    SellerLogService::getInstance()->log($this->sellerId, $this->shopId, $this->userId, 'member_card/add', 'user' ,'新建会员卡');
                    $this->ajaxReturn(array('code'=>1000,'msg'=>'success'));
                }
                else 
                {
                    throw new Exception('新建会员卡失败');
                }
                
            }
            catch (Exception $e)
            {
                $this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
            }
            
        }
        else 
        {
            //查询商家优惠券
            $coupon = Deposit_CouponService::manualCouponList($this->shopId, 1, 3, '', 1, 1000);
            
            $hash['coupon_list'] = $coupon['lists'];
            $token = Tool_Form::createToken();
            $this->assign('token', $token);
            $this->assign('loadModuleScript', true);
            $this->display($hash, 'member/card/increase.html');
        }
    }



    /**
     * 删除会员卡
     */
    public function ajaxDeleteAction()
    {
        try 
        {
            if(!$this->_request->isXmlHttpRequest())
            {
                throw new Exception('非法请求');
            }
            $cardId = $this->_request->getPost('id');
            //验证身份
            $cardInfo = $this->cardModel->find(array('id'=>$cardId,'seller_id'=>$this->sellerId));
            if(empty($cardInfo))
            {
                throw new Exception('身份非法');
            }

            /**
            //是否领取
            $id = $this->memberCardModel->find(array('card_id'=>$cardId),array('id'));
            if($id)
            {
                throw new Exception('有人领取该会员卡，无法删除');
            }
             **/

            $ids = $this->memberCardModel->select(array('card_id'=>$cardId),array('fans_id'));
            //删除
            //$res = $this->cardModel->deleteData(array('id'=>$cardId));

            $res = $this->cardModel->updateData(array('status' => 0), array('id'=>$cardId));
            if($res === false)
            {
                throw new Exception('删除失败，请稍后再试');
            }

            //将删除会员卡会员变为删除会员
            $userMemberModel = new U_MemberCardModel();
            $where = array(
                'card_id' => $cardId,
                'seller_id'=>$this->sellerId
            );
            $data['card_id'] = 0;
            $data['card_name'] = '非会员';
            $data['before_card_id'] = $cardId;
            $data['pay_type'] = 5;
            $data['status'] = 3;
            $data['update_time'] = SYS_TIME;
            $userMemberModel->updateData($data,$where);
            $fansModel = new U_FansModel($this->sellerId);
            $data = array('level' => '0','card_id' => '0');
            $fansModel->updateData($data,$where);
            //非会员修改为会员
            $shopFansModel = new U_ShopFansModel($this->sellerId);
            $fansId = '';
            if($ids)
            {
                foreach($ids as $key => $value)
                {
                    $fansId .= $value['fans_id'].',';
                }
            }
            $where = array('fans_id'=>array('in',rtrim($fansId,',')),'seller_id' => $this->sellerId);
            if(!$this->getCurrentUser()->isChiefShop())
            {
                $where['shop_id'] = $this->shopId;
            }
            $shopFansModel->updateData(array('is_member' => 0),$where);

            SellerLogService::getInstance()->log($this->sellerId, $this->shopId, $this->userId, $this->controller . '/' . $this->action, 'user' ,'删除会员卡');
            $this->ajaxReturn(array('code'=>1000,'msg'=>'success'));
        }
        catch (Exception $e)
        {
            $this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
        }
        
    }

    /**
     * @author qiankun
     * @Fuction name updateAction
     * @description  编辑会员卡
     */
    public function updateAction()
    {
        if($this->_request->isXmlHttpRequest())
        {
            try 
            {
                $postData = $this->_request->getPost();
                if(!Tool_Form::checkToken($postData['token']))
                {
                    throw new Exception('请勿重复提交');
                }
                if(!$postData['card_name'])
                {
                    throw new Exception('会员卡名称不能为空');
                }
                //验证身份
                $cardInfo = $this->cardModel->find(array('id'=>$postData['id'],'seller_id'=>$this->sellerId));
                if(empty($cardInfo))
                {
                    throw new Exception('身份非法');
                }
                //验证等级是否重复
                $data['level'] = (int)$postData['level'];
                if($data['level'] > 99)
                {
                	throw new Exception('会员等级最大不超过99');
                }
                if(!$this->checkLevel($data['level'], $postData['id']) || $data['level'] <= 0 )
                {
                    throw new Exception('会员等级重复，请重新填写');
                }

                //付费会员验证
                if( in_array($cardInfo['type'],array(0,1)) && $postData['member_card_type'] == 2)
                {
                    throw new Exception('不能修改付费类型');
                }
                if( in_array($cardInfo['type'],array(2,3,4)) && $postData['member_card_type'] == 1)
                {
                    throw new Exception('不能修改付费类型');
                }

                if($postData['member_card_type'] == 1)
                {
                    $data['type'] = 1;
                }
                else if( $postData['member_card_type'] == 2)
                {
                    if(!$pay_type = intval($postData['pay_type']))
                    {
                        throw new Exception('请填写付费类型');
                    }
                    else
                    {
                        $payDiscount = $postData['pay_discount'];
                        if($payDiscount > 10 || $payDiscount < 0)
                        {
                            throw new Exception('续费折扣必须在0-10之间');
                        }
                        if($postData['price'] == '')
                        {
                            throw new Exception('未填写金额');
                        }
                        //正整数包含0
                        if(!Tool_Validator::isPositiveInteger($postData['price']) && $postData['price'] !=0)
                        {
                            throw new Exception('付费金额必须为整数');
                        }
                        if(!is_numeric($postData['price']) || $postData['price'] < 0)
                        {
                            throw new Exception('请填写正确的金额');
                        }
                        if($postData['price']* $postData['pay_discount'] != 0 && $postData['pay_discount'] <0.01)
                        {
                            throw new Exception( '折扣后的价格不能低于0.01');
                        }
                        $data['pay_discount'] = $payDiscount*10;
                        $data['price'] = intval($postData['price']);
                        switch($pay_type)
                        {
                            case 1:
                                $data['type'] = 2;
                                $data['pay_month'] = 0;
                                $data['pay_start_time'] = 0;
                                $data['pay_end_time'] = 0;
                                break;
                            case 2:
                                $data['type'] = 3;
                                if($pay_month = intval($postData['pay_month']))
                                {
                                    $data['pay_month'] = $pay_month; //时间区间
                                    $data['pay_start_time'] = 0;
                                    $data['pay_end_time'] = 0;
                                }
                                else
                                {
                                    throw new Exception('请填写月份');
                                }
                                break;
                            case 3:
                                $data['type'] = 4;
                                if(!$postData['end_time'] || !$postData['start_time'])
                                {
                                    throw new Exception('填写开始和结束时间');
                                }
                                if($postData['end_time'] < $postData['start_time'])
                                {
                                    throw new Exception('结束时间必须大于开始时间');
                                }
                                $data['pay_start_time'] =  $postData['start_time'] ? strtotime($postData['start_time']): 0;
                                $data['pay_end_time'] = $postData['end_time'] ? strtotime($postData['end_time'])+24*3600-1 : 0;
                                $data['pay_month'] = 0;
                                break;
                            default:
                                throw new Exception('未选择对应的付费类型');
                        }
                    }
                }
                else
                {
                    throw new Exception('未选择会员卡类型');
                }
                //付费会员验证end

                $data['background_color'] = $postData['background_color'];
                $data['card_name'] = $postData['card_name'];
                //$data['type'] = $postData['type'];
                $data['pic_id'] = $postData['pic_id']?$postData['pic_id']:null;
                $data['discount'] = $postData['discount']*10;
                $data['is_freepost'] = $postData['is_freepost'];
                $postData['fans_consumption'] && $data['fans_consumption'] = $postData['fans_consumption'];
                $postData['fans_times'] && $data['fans_times'] = $postData['fans_times'];
                $postData['integral'] && $data['fans_integral'] = $postData['integral'];
                
                $data['reward_integral'] = $postData['reward_integral']?$postData['reward_integral']:null;
                $data['reward_consumption'] = $postData['reward_consumption']?$postData['reward_consumption']:null;
                $data['reward_coupon_id'] = $postData['reward_coupon_id']?$postData['reward_coupon_id']:null;                
                $data['phone'] = $postData['phone'];
                $data['terms'] = $postData['terms'];
                $data['update_user'] = $this->userId;
                $data['update_time'] = SYS_TIME;
                $dataStr = '';
                foreach ($data as $k=>$v)
                {
                	$str = " ";
                	if($v === null)
                	{
                		$str .= "`$k` = null ,";
                	}
                	else 
                	{
                		$str .= "`$k` = '$v' ,";
                	}
                	
                	$dataStr .= $str;
                }
                $dataStr = rtrim($dataStr, ',');
                $sql = "UPDATE `ts_user_member_card_attr` SET $dataStr WHERE `id` = {$postData['id']}";
                $res = $this->cardModel->execute($sql);

                if($res === false)
                {
                    throw new Exception('更新失败，请稍后再试');
                }
                $key = CacheKey::getCardInfoById($postData['id']);
                mc_unset($key);
                SellerLogService::getInstance()->log($this->sellerId, $this->shopId, $this->userId, 'member_card/update', 'user' ,'修改会员卡');
                $this->ajaxReturn(array('code'=>1000,'msg'=>'success'));
            }
            catch (Exception $e)
            {
                $this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
            }
        }
        else  
        {  
            $id = $this->_request->getQuery('card_id');
            $cardInfo = User_CardService::getCardInfo($id);
            if($cardInfo['seller_id'] != $this->sellerId)
            {
                $this->showMessage(2, '无法编辑此会员卡', $_SERVER['HTTP_REFERER'], '没有权限', 5);
            }
            $picModel = new PicDataModel();
            $picInfo = $picModel->getInfoById($cardInfo['pic_id']);
            $cardInfo['img'] = $picInfo['org'];
            $cardInfo['token'] = Tool_Form::createToken();
            $cardInfo['reward_consumption'] = $cardInfo['reward_consumption'] ? floatval($cardInfo['reward_consumption']) : null;
            //查询优惠券列表
            $coupon = Deposit_CouponService::manualCouponList($this->shopId, 1, 3, '', 1, 1000);
            $hash['coupon_list'] = $coupon['lists'];
            $cardInfo['pay_start_time'] = $cardInfo['pay_start_time'] ? date('Y-m-d',$cardInfo['pay_start_time']) : '';
            $cardInfo['pay_end_time'] = $cardInfo['pay_end_time'] ? date('Y-m-d',$cardInfo['pay_end_time']-24*3600+1) : '';
            $cardInfo['pay_discount'] = $cardInfo['pay_discount']/10;
            $cardInfo['price'] = floatval($cardInfo['price']);
            //查询是否是最低等级
            $resId = $this->cardModel->find(array('seller_id'=>$this->sellerId,'level'=>array('lt',$cardInfo['level'])), array('id'));
            $hash['is_low'] = $resId ? 0 : 1;
            $hash['data'] = $cardInfo;
            $this->assign('loadModuleScript', true);
            $this->display($hash, 'member/card/updata.html');
        }
        
    }
    
    //等级变更记录
    public function levelChangeRecordAction()
    {  
        $params = $this->_request->getQuery();
        $page = max(intval($params['page']),1);
        $pageSize = 10;
        $where['seller_id'] = $this->sellerId;
        $where['before_card_id'] = array('gt',0);;
        if(!empty($params['start_time']) && !empty($params['end_time']))
        {
            $startTime = (int)strtotime($params['start_time']);
            $endTime = (int)strtotime($params['end_time']);
            $where['update_time'] = array('between', "$startTime,$endTime");
        }
        elseif(!empty($params['start_time']) && empty($params['end_time']))
        {
            $startTime = (int)strtotime($params['start_time']);
            $where['update_time'] = array('EGT', $startTime);
        }
        elseif(empty($params['start_time']) && !empty($params['end_time']))
        {
            $endTime = (int)strtotime($params['end_time']);
            $where['update_time'] = array('ELT', $endTime);
        }
        
        $list = $this->memberCardModel->listPage($where, array('fans_id','card_id','update_time','before_card_id'),'update_time desc', $page, $pageSize);
        
        if(!empty($list))
        {
            foreach ($list as $k=>$v)
            {
                //获取粉丝信息
                $userInfo = WeiXin_WxUserService::getFansInfo($v['fans_id'], $this->sellerId);
                $list[$k]['user_name'] = $userInfo['nick_name'];
                unset($userInfo);
                //获取当前会员卡信息
                $cardInfo = User_CardService::getCardInfo($v['card_id']);
                $list[$k]['card_name'] = $cardInfo['card_name'];
                unset($cardInfo);
                //获取之前会员卡信息
                $cardInfo = User_CardService::getCardInfo($v['before_card_id']);
                $list[$k]['before_card_name'] = $cardInfo['card_name'];
                unset($cardInfo);
                
                $list[$k]['update_time'] = date('Y-m-d H:m:s',$v['update_time']);
                
            }
        }
        $total = $this->memberCardModel->count($where);
        
        $where['start_time'] = $params['start_time'];
        $where['end_time'] = $params['end_time'];
        $data['list'] = $list;
        $data['where'] = $where;
        $data['total'] = $total;
        $data['page'] = $page;
        $data['totalPage'] = ceil($total / $pageSize);
        
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/card/level-change-record.html');
    }
    
    /**
     * 验证等级是否重复
     */
    public function checkLevel($level, $cardId = null)
    {
    	if($level > 100 || $level < 1)
    	{
    		return false;
    	}
        $info = $this->cardModel->select(array('seller_id'=>$this->sellerId,'level'=>$level,'status'=>1), array('id'));
        if($cardId)
        {
            if(count($info) > 1 || (count($info) == 1 && $info[0]['id'] != $cardId))
            {
                return false;
            }
        }
        else 
        {
            if($info)
            {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 验证积分是否合法
     * 理论上，等级越高，积分越高
     */
    public function checkIntegral($int, $level)
    {
    	$sql = 'SELECT
					id
				FROM
					ts_user_member_card_attr
				WHERE
					seller_id = '.$this->sellerId.'
				AND `status` = 1 
				AND `fans_integral` > 0 
				AND (
					(
						`level` < '.$level.'
						AND fans_integral >= '.$int.'
					)
					OR (
						`level` > '.$level.'
						AND fans_integral <= '.$int.'
					)
				)';
    	$res = $this->cardModel->fetchAll($sql);
    	
    	return !empty($res) ? false : true;
    }
    
    /**
     * @author zouhao <zouhao@dodoca.net>
     * @description 会员申请设置页面
     * @datetime 2016年4月21日13:53:12
     */
    public function memberSetAction()
    {
        $sellerId = $this->getCurrentUser()->getSellerId();
        $where['seller_id'] = $sellerId;
        $where['status'] = 1;
        $configModel = new U_ApplyConfigModel();
        $list = $configModel->select($where, array('*'));
        $data = array();
        !empty($list) && $data['list'] = $list;
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/default/member-set.html');
    }

    /**
     * @author zouhao <zouhao@dodoca.net>
     * @description 保存申请设置
     * @datetime 2016年4月21日13:53:12
     */
    public function ajaxSaveConfigAction()
    {
        try{
            if(!$this->_request->isXmlHttpRequest() || !$this->_request->isPost()){
                throw new Exception('非法访问');
            }
            else{
                $sellerId = $this->getCurrentUser()->getSellerId();
                $configArr = $this->_request->getPost('arr');
                $data = array();
                $configModel = new U_ApplyConfigModel();
                if(!empty($configArr)){
                    foreach($configArr as $key => $value){
                        //插入数组
                        if(!$value['num']){
                            $data[] = array(
                                'seller_id' => $sellerId,
                                'create_time' => time(),
                                'status' => 1,
                                'type' => $value['type'],
                                'name' => $value['name'],
                                'con_type'=>$value['con_type']?$value['con_type']:0,
                                'required'=>$value['required']
                            );
                        }
                        //更新操作
                        else{
                            $set = array(
                                'type' => $value['type'],
                                'name' => $value['name'],
                                'con_type'=>$value['con_type']?$value['con_type']:0,
                                'required'=>$value['required']
                            );
                            $configModel->updateData($set, array('id' => intval($value['num'])));
                            SellerLogService::getInstance()->log($this->getCurrentUser()->getSellerId(), $this->getCurrentUser()->getShopId(), $this->getCurrentUser()->get('id'), 2, 'member_default', '更新会员申请设置');
                        }
                    }
                    if(!empty($data)){
                        $configModel->insertAll($data);
                        SellerLogService::getInstance()->log($this->getCurrentUser()->getSellerId(), $this->getCurrentUser()->getShopId(), $this->getCurrentUser()->get('id'), 1, 'member_default', '新增会员申请设置');
                    }
                }
                $this->ajaxReturn(array(
                    'code' => 1,
                    'msg' => '保存成功'
                ));
            }
        }
        catch(Exception $e){
            $this->ajaxReturn(array(
                'code' => -1,
                'msg' => $e->getMessage()
            ));
        }
    }
    
    /**
     * @author zouhao <zouhao@dodoca.net>
     * @description 删除申请设置
     * @datetime 2016年4月21日13:53:12
     */
    public function ajaxDeleteConfigAction()
    {
        try{
            if(!$this->_request->isXmlHttpRequest() || !$this->_request->isPost()){
                throw new Exception('非法访问');
            }
            else{
                $id = intval($this->_request->getPost('id'));
                if(!$id){
                    throw new Exception('参数缺失');
                }
                else{
                    $configModel = new U_ApplyConfigModel();
                    $res = $configModel->updateData(array('status' => -1), array('id' => $id));
                    if($res !== false){
                        SellerLogService::getInstance()->log($this->getCurrentUser()->getSellerId(), $this->getCurrentUser()->getShopId(), $this->getCurrentUser()->get('id'), 3, 'member_default', '删除会员申请设置');
                        $this->ajaxReturn(array(
                            'code' => 1,
                            'msg' => '删除成功'
                        ));
                    }
                    else{
                        throw new Exception('数据库错误,请稍后再试');
                    }
                }
            }
        }
        catch(Exception $e){
            $this->ajaxReturn(array(
                'code' => -1,
                'msg' => $e->getMessage()
            ));
        }
    }
    
    
    
}

